﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace TheHomeOfMiao
{
    public partial class Study : Form
    {
        string type;
        public static System.Timers.Timer aTimer = new System.Timers.Timer();
        public Study(string t1,string t2)
        {
            InitializeComponent();
            type = t1;
            studyTime.Text = t2;
            if (type == "N")
            {
                aTimer.Elapsed += new ElapsedEventHandler(addPollingEvent); //到达时间的时候执行事件；
                aTimer.Interval = 1000; // 设置引发时间的时间间隔 此处设置为1秒（1000毫秒）
                aTimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
                aTimer.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件；
                aTimer.Start();
            }
            else
            {
                aTimer.Elapsed += new ElapsedEventHandler(subPollingEvent); //到达时间的时候执行事件；
                aTimer.Interval = 1000; // 设置引发时间的时间间隔 此处设置为1秒（1000毫秒）
                aTimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
                aTimer.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件；
                aTimer.Start();
            }
        }
        
        private void addPollingEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            addTime();
        }

        private void addTime()
        {
            //创建一个委托，用于封装一个方法，在这里是封装了 控制更新控件 的方法
            Action invokeAction = new Action(addTime);
            //判断操作控件的线程是否创建控件的线程
            //调用方调用方位于创建控件所在的线程以外的线程中，如果在其他线程则对控件进行方法调用时必须调用 Invoke 方法
            if (this.InvokeRequired)
            {
                //与调用线程不同的线程上创建（说明您必须通过 Invoke 方法对控件进行调用）
                this.Invoke(invokeAction);
            }
            else
            {
                //窗体线程，即主线程
                string[] t = this.studyTime.Text.ToString().Split(':');
                int hour = int.Parse(t[0]), minute = int.Parse(t[1]), second = int.Parse(t[2]);
                second++;
                if (second == 60)
                {
                    second = 0;
                    minute++;
                }
                if (minute == 60)
                {
                    minute = 0;
                    hour++;
                }
                string setTime = "";
                setTime += hour;
                setTime += ":";
                setTime += minute;
                setTime += ":";
                setTime += second;
                studyTime.Text = setTime;
            }
        }
        private void subPollingEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            subTime();
        }

        private void subTime()
        {
            if (studyTime.Text.ToString() == "0:0:0") return;
            //创建一个委托，用于封装一个方法，在这里是封装了 控制更新控件 的方法
            Action invokeAction = new Action(subTime);
            //判断操作控件的线程是否创建控件的线程
            //调用方调用方位于创建控件所在的线程以外的线程中，如果在其他线程则对控件进行方法调用时必须调用 Invoke 方法
            if (this.InvokeRequired)
            {
                //与调用线程不同的线程上创建（说明您必须通过 Invoke 方法对控件进行调用）
                this.Invoke(invokeAction);
            }
            else
            {
                //窗体线程，即主线程
                string[] t = studyTime.Text.ToString().Split(':');
                int hour = int.Parse(t[0]), minute = int.Parse(t[1]), second = int.Parse(t[2]);
                if (second == 0)
                {
                    if (minute == 0)
                    {
                        minute = 60;
                        hour--;
                    }
                    second = 60;
                    minute--;
                }
                second--;
                string setTime = "";
                setTime += hour;
                setTime += ":";
                setTime += minute;
                setTime += ":";
                setTime += second;
                studyTime.Text = setTime;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //using (SQLiteConnection connection=new SQLiteConnection(@"DataSource=..\..\Resources\TheHomeOfMiao1.db;Version=3"))
            //{
            //    connection.Open();
            //    using (SQLiteCommand command=new SQLiteCommand("select * from study where id='"+StartStudy.count+"'",connection))
            //    {
            //        SQLiteDataReader reader = command.ExecuteReader();
            //        reader.Read();
            //        NewNote newNote=new NewNote(StartStudy.count,reader["checkGoal"].ToString());
            //        Thread th = new Thread(delegate () { newNote.ShowDialog(); });
            //        th.Start();
            //        reader.Close();
            //    }
            //    connection.Close();
            //}
            Thread th = new Thread(delegate () { new NoteBook().ShowDialog(); });
            th.Start();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            aTimer.Stop();
            new SetRest().ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)//结束
        {
            aTimer.Stop();
            string time;
            if (type == "N")
            {
                time = studyTime.Text.ToString();
                MessageBox.Show("喵喵自习结束，自习时长为" + studyTime.Text.ToString());
                using (SQLiteConnection connection=new SQLiteConnection(@"DataSource=..\..\Resources\TheHomeOfMiao1.db;Version=3"))
                {
                    connection.Open();
                    using (SQLiteCommand command=new SQLiteCommand("update study set time='"+time+"', state='Y' where id='"+StartStudy.count+"'",connection))
                    {
                        command.ExecuteNonQuery();
                    }
                    connection.Close();
                }
            }
            if (type == "Y")
            {
                using (SQLiteConnection connection=new SQLiteConnection(@"DataSource=..\..\Resources\TheHomeOfMiao1.db;Version=3"))
                {
                    connection.Open();
                    using (SQLiteCommand command=new SQLiteCommand("select * from study where id='"+StartStudy.count+"'",connection))
                    {
                        SQLiteDataReader reader = command.ExecuteReader();
                        reader.Read();
                        string goalTime = reader["time"].ToString();
                        string actualTime = studyTime.Text.ToString();
                        string[] g = goalTime.Split(':');
                        string[] a = actualTime.Split(':');
                        int hourG=int.Parse(g[0]), minuteG=int.Parse(g[1]), secondG=int.Parse(g[2]);
                        int hourA = int.Parse(a[0]), minuteA = int.Parse(a[1]), secondA = int.Parse(a[2]);
                        int hour, minute, second;
                        if (secondG < secondA)
                        {
                            secondG += 60;
                            minuteG--;
                        }
                        second = secondG - secondA;
                        if (minuteG < minuteA)
                        {
                            minuteG += 60;
                            hourG--;
                        }
                        minute = minuteG - minuteA;
                        hour = hourG - hourA;
                        time = "" + hour + ":" + minute + ":" + second;
                        if (actualTime=="0:0:0")
                        {
                            MessageBox.Show("喵喵自习结束，自习时长为" + goalTime);
                            using (SQLiteCommand command1 = new SQLiteCommand("update study set time='" + time + "', state='Y' where id='" + StartStudy.count + "'", connection))
                            {
                                command1.ExecuteNonQuery();
                            }
                        }
                        else
                        {
                            MessageBox.Show("钓鱼自习结束，自习时长为" + time);
                            using (SQLiteCommand command1 = new SQLiteCommand("update study set time='" + time + "', state='N' where id='" + StartStudy.count + "'", connection))
                            {
                                command1.ExecuteNonQuery();
                            }
                        }
                        reader.Close();
                    }
                    connection.Close();
                }
            }
            Thread th = new Thread(delegate () { new Main().ShowDialog(); });
            th.Start();
            this.Close();
        }
    }
}
